<?php

/**
 * Parse requested address and show particular tab
 *
 * @author Aurelijus Banelis
 */
$started = microtime(true);
/* Loading common libraries */
require 'Init/common.php';
include 'Init/database.php';
include 'GUI/Functions/gui_functions.php';
include 'GUI/Design/MainDesign.php';
DB::connect();

/* Login, logged_in & logout section */
require 'Processing/Login/login_processing.php';
if(array_key_exists('logout', $_GET)){
    logout();
}

if (isset($_POST['real_action_script']) && $_POST['real_action_script'] == 'Processing/Login/login_processing.php') {
    include_once($_POST['real_action_script']);
    unset($_POST['real_action_script']);
}

if(!logged_in()){
    include 'GUI/Login/login.php';
    exit;
}

$help_links = Array();
$sidebar_content = "";

/* Form data and Ajax requests processing */
//FIXME: security
if (isset($_POST['real_action_script']) && file_exists($_POST['real_action_script'])) {
    if (isset($_POST['ajax_request']) && $_POST['ajax_request'] == 'true') {
        include_once($_POST['real_action_script']);
        exit();
    } else {
        //ob_start();
        include_once($_POST['real_action_script']);
        //FIXME: when importing data: "failed to delete buffer. No buffer to delete"
        //@ob_clean();
    }
}

/* Parsing address */
$requested_tab = Addresing::get_requested_tab();

/* List of tabs */
$tabs = '';
$tabs_array = include('GUI/Tabs/list.php');

/* Default command */
if (!in_array($requested_tab, array_keys($tabs_array))) {
    $requested_tab = array_search(current($tabs_array), $tabs_array);
}

$print_version = Addresing::isPrintVersion($tabs_array, $file);

/* Current command */
list($file, $page_title) = explode('|', $tabs_array[$requested_tab]);

ob_start();
$print_version = Addresing::isPrintVersion($tabs_array, $print_view);
if ($print_version) {
    include $print_view;
} else {
    include "GUI/$file";
}
$main_content = ob_get_clean();

$help = "";
if (isset($helpHTML)) {
    $help = $helpHTML;
}


/* Finalising */
DB::close();
$time = round((microtime(true) - $started), 2);
$footer = "Užtruko $time s.";
if (function_exists('memory_get_peak_usage')) {
    $ram = round(memory_get_peak_usage() / 1024, 2);
    $footer .= "\nAtminties suvartojo: ";
    if ($ram < 1024) {
        $footer .= "$ram kB";
    } else {
        $ram = round($ram / 1024, 2);
        $footer .= "$ram MB";
    }
}

if ($print_version) {
    include 'GUI/Design/print_design.php';
} else {
    include 'GUI/Design/main_design.php';
}
